package com.loong.musicdemo.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.loong.musicdemo.PlaySongActivity;
import com.loong.musicdemo.util.dataDeal.MusicDeal;
import com.loong.musicdemo.util.enumutil.PlaySongType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static org.litepal.LitePalApplication.getContext;

/**
 * 自助播放服务
 * 1、实现音乐自动播放功能
 * 2、实现音乐的一些常见逻辑
 * 3、音乐的后台播放（不需要借助活动就可以）
 * 4、优先使用本地资源进行播放
 * 5、支持当前列表的添加以及修改
 */
public class AutoPlayService extends Service {
    public static final String TAG = "AutoPlayService";
    //处理自动播放的handler
    @SuppressLint("HandlerLeak")
    private static Handler changeHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData(); //获取从子线程发送过来的音乐播放进度
            int duration = bundle.getInt("duration");                  //歌曲的总时长
            int currentPosition = bundle.getInt("currentPosition");//歌曲当前进度
            if (!player.isPlaying() && currentPosition > duration)
                autoPlay();
        }
    };
    @SuppressLint("HandlerLeak")
    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData(); //获取从子线程发送过来的音乐播放进度
            String id = bundle.getString("songId");
            boolean add = false;
            if (!ids.contains(id)) {
                add = ids.add(id);
            }
            if (add) {
                //添加成功
                Toast.makeText(getContext(), "添加歌曲成功", Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(getContext(), "该歌曲已在播放列表", Toast.LENGTH_SHORT).show();
        }
    };
    private static String currentId;//当前播放的音乐id
    private static Timer timer;//计时器
    private static MediaPlayer player = new MediaPlayer();//音乐播放器
    private static String musicUrl = "";//音乐播放地址
    public static List<String> ids = new ArrayList<>();//当前播放列表

    public AutoPlayService() {
    }

    public class MusicControl extends Binder {
        public void playMusic(String songId) {//通过id播放歌曲
            new Thread(() -> {
                currentId = songId;
                musicUrl = MusicDeal.getSongInfoById(songId).getPlayUrl();//获取播放地址
                try {
                    player = new MediaPlayer();
                    if (player.isPlaying()) {//确保在prepare()之前调用了stop()
                        player.stop();
                        player.reset();
                    }
                    player.setDataSource(musicUrl);
                    player.setOnPreparedListener(listener);
                    player.prepareAsync();
                    addTimer();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }).start();
        }

        MediaPlayer.OnPreparedListener listener = MediaPlayer::start;

        public void play() {
            try {
                player.reset();//重置音乐播放器
                //加载多媒体文件
                try {
                    player.setDataSource(musicUrl);
                    player.start();//开始播放
                    addTimer();//添加计时器
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void pausePlay() {
            player.pause();//暂停播放音乐
        }

        public void continuePlay() {
            player.start();//继续播放音乐
        }

        public void seekTo(int progress) {
            player.seekTo(progress);//设置音乐的播放位置
        }

        /**
         * 播放下一首
         *
         * @param type 当前播放类型
         */
        public void playNextSong(PlaySongType type) {
            nextSong(type);
        }

        /**
         * 播放下一首歌
         *
         * @param types 当前播放类型
         */
        public void playLastSong(PlaySongType types) {
            lastSong(types);
        }
    }

    /**
     * 上一首
     *
     * @param type 播放状态
     */
    private void lastSong(PlaySongType type) {
        int i = ids.indexOf(currentId);//当前音乐的索引
        if (ids.size() > 0) {
            switch (type) {
                case SINGLES:
                case SEQUENTIAL:
                    //单曲循环和循环播放都是直接播放下一首
                    if (i == 0) {
                        //当播放到第一首歌时
                        i = ids.size() - 1;
                    } else {
                        i--;
                    }
                    break;
                case SHUFFLE:
                    i = (int) (Math.random() * ids.size());
                    break;
                default:
                    break;
            }
            currentId = ids.get(i);
            new Thread(() -> {
                musicUrl = MusicDeal.getSongInfoById(currentId).getPlayUrl();//获取播放地址
                try {
                    player = new MediaPlayer();
                    if (player.isPlaying()) {//确保在prepare()之前调用了stop()
                        player.stop();
                        player.reset();
                    }
                    player.setDataSource(musicUrl);
                    changeSong(currentId);//切换歌曲
                    MediaPlayer.OnPreparedListener listener = MediaPlayer::start;
                    player.setOnPreparedListener(listener);
                    player.prepareAsync();
                    addTimer();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }).start();
        }
    }

    /**
     * 下一首
     *
     * @param type 播放状态
     */
    private void nextSong(PlaySongType type) {
        int i = ids.indexOf(currentId);//当前音乐的索引
        if (ids.size() > 0) {
            switch (type) {
                case SINGLES:
                case SEQUENTIAL:
                    //单曲循环和循环播放都是直接播放下一首
                    if (i == ids.size() - 1) {
                        //当播放到最后一首歌时
                        i = 0;
                    } else {
                        i++;
                    }
                    break;
                case SHUFFLE:
                    i = (int) (Math.random() * ids.size());
                    break;
                default:
                    break;
            }
            currentId = ids.get(i);
            new Thread(() -> {
                musicUrl = MusicDeal.getSongInfoById(currentId).getPlayUrl();//获取播放地址
                try {
                    player = new MediaPlayer();
                    if (player.isPlaying()) {//确保在prepare()之前调用了stop()
                        player.stop();
                        player.reset();
                    }
                    player.setDataSource(musicUrl);
                    changeSong(currentId);//切换歌曲
                    MediaPlayer.OnPreparedListener listener = MediaPlayer::start;
                    player.setOnPreparedListener(listener);
                    player.prepareAsync();
                    addTimer();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }).start();
        }
    }

    public static void addTimer() {
        //添加计时器用于设置音乐播放器的进度同步
        if (timer == null) {
            timer = new Timer();//创建计时器对象
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    //获取信息发送到音乐播放活动中
                    if (player == null) return;
                    int duration = player.getDuration();              //获取歌曲总时长
                    int currentPosition = player.getCurrentPosition();//获取播放进度
                    Message msg = PlaySongActivity.handler.obtainMessage();//创建消息对象
                    //将音乐的总时长和播放进度封装至消息对象中
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);//毫秒时间
                    bundle.putInt("currentPosition", currentPosition);//当前播放进度
                    msg.setData(bundle);
                    //将消息发送到主线程的消息队列
                    PlaySongActivity.handler.sendMessage(msg);
                    msg = AutoPlayService.changeHandler.obtainMessage();
                    msg.setData(bundle);
                    AutoPlayService.changeHandler.sendMessage(msg);
                }
            };
            timer.schedule(task, 5, 500);//在开始后的2毫秒，之后每隔200毫秒执行一下刷新
        }
    }


    /**
     * 自动播放音乐--自动播放循环列表的下一首
     */
    private static void autoPlay() {
        int i = ids.indexOf(currentId);//当前音乐的索引
        if (ids.size() > 0) {
            if (i == ids.size() - 1) {
                //当播放到最后一首歌时
                i = 0;
            } else {
                i++;
            }
            int finalI = i;
            new Thread(() -> {
                currentId = ids.get(finalI);
                musicUrl = MusicDeal.getSongInfoById(currentId).getPlayUrl();//获取播放地址
                try {
                    player = new MediaPlayer();
                    if (player.isPlaying()) {//确保在prepare()之前调用了stop()
                        player.stop();
                        player.reset();
                    }
                    player.setDataSource(musicUrl);
                    changeSong(currentId);//切换歌曲
                    MediaPlayer.OnPreparedListener listener = MediaPlayer::start;
                    player.setOnPreparedListener(listener);
                    player.prepareAsync();
                    addTimer();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }).start();
        }
    }

    private static void changeSong(String currentId) {
        //将消息发送到主线程的消息队列
        Message msg = PlaySongActivity.handler.obtainMessage();//创建消息对象
        Bundle bundle = new Bundle();
        bundle.putString("songId", currentId);
        msg.setData(bundle);
        PlaySongActivity.changeSongHandler.sendMessage(msg);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl();//返回绑定
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();//初始化音乐播放器
        Log.i(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player == null) {
            return;
        }
        if (player.isPlaying())
            player.stop();//停止
        player.release();//释放资源
        player = null;//player置空
    }
}
